package com.wzy.authority.base.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.wzy.authority.domain.SysPermission;
import com.wzy.authority.domain.SysUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: authorityManagement
 * @description: 继承SysUser并且实现security的UserDetails
 * @author: 1
 * @create: 2020-03-24 21:21
 **/
@Data
@Slf4j
public class LoginUser extends SysUser implements UserDetails {


    //拥有的权限列表
    private List<SysPermission> sysPermissions;


    /**
     * 认证的权限绑定
     * GrantedAuthority:已认证的权限
     *
     * @return
     */
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        log.info("GrantedAuthority 做出反应");
        //将权限转为流再过滤
        return sysPermissions.parallelStream()
                //判断权限不为空
                .filter(permission -> !StringUtils.isEmpty(permission.getPermission()))
                //先将权限添加到GrantedAuthority中
                .map(permission -> {
                    return new SimpleGrantedAuthority(permission.getPermission());
                })
                //转化为set形式
                .collect(Collectors.toSet());
    }


    /**
     * 判断用户是否过期
     *
     * @return
     */
    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 判断账户是否被锁定
     *
     * @return
     */
    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return !Status.LOCKED.equals(getStatus());
    }


    /**
     * 是否已过期
     *
     * @return
     */
    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }


    /**
     * 判断是否被激活
     *
     * @return
     */
    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }
}
